import BulletController from "./BulletController";

const {ccclass, property} = cc._decorator;

@ccclass
export default class CannonLayer extends cc.Component {


    private m_degree:number = 90;

    
    onLoad () 
    {

    }

    start () 
    {

        this.addEvents();
        this.schedule(this.run_fire.bind(this),0.5);

    }


    run_fire()
    {
        // cc.log("run_fire!!");
        var bullet = BulletController.getInstace().create_bullet();
        this.node.getChildByName("bulletLayer").addChild(bullet);
        bullet.x = this.node.getChildByName("gun").x;
        bullet.y = this.node.getChildByName("gun").y;
        // bullet.getComponent("Bullet");
        bullet.getComponent("Bullet").setAngle(this.m_degree);


    }

    private addEvents()
    {

        cc.find("Canvas").on(cc.Node.EventType.TOUCH_START, function(e) 
        {
            var globalPos = e.getLocation();
            var currentPos = this.node.getChildByName("gun").convertToWorldSpaceAR(cc.v2(0,0));
            var posDir = globalPos.sub(currentPos);
            var len = posDir.mag();
            var dir:any = {};
            dir.x = posDir.x / len;
            dir.y = posDir.y / len;
            var r = Math.atan2(dir.y,dir.x);
            var degree = r * 180 / Math.PI;
            this.m_degree = degree;
            this.node.getChildByName("gun").angle = degree - 90;



        }.bind(this));
                
        cc.find("Canvas").on(cc.Node.EventType.TOUCH_MOVE, function(e)
        {
            var globalPos = e.getLocation();
            var currentPos = this.node.getChildByName("gun").convertToWorldSpaceAR(cc.v2(0,0));
            var posDir = globalPos.sub(currentPos);
            var len = posDir.mag();
            var dir:any = {};
            dir.x = posDir.x / len;
            dir.y = posDir.y / len;
            var r = Math.atan2(dir.y,dir.x);
            var degree = r * 180 / Math.PI;
            this.node.getChildByName("gun").angle = degree - 90;
            this.m_degree = degree;

            console.log("touch_move");
        }.bind(this));

        cc.find("Canvas").on(cc.Node.EventType.TOUCH_END, function(e)
        {
            
        }.bind(this));

        cc.find("Canvas").on(cc.Node.EventType.TOUCH_CANCEL, function(e)
        {

        }.bind(this));
        
    }




    // update (dt) {}
}
